package com.ckj.bloghunter.domain.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.commons.lang3.StringEscapeUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.ckj.bloghunter.config.BaseSystemConfig;
import com.ckj.bloghunter.dao.dataobject.SmallTechnologyBlog;
import com.ckj.bloghunter.dao.mapper.SmallTechnologyBlogMapper;
import com.ckj.bloghunter.domain.service.BlogComponentService;
import com.ckj.bloghunter.domain.service.common.YesEnum;
import com.ckj.bloghunter.dto.request.BaseInsertDTO;
import com.ckj.bloghunter.dto.request.PreviewHunterBlogRequest;
import com.ckj.bloghunter.dto.response.PreviewHunterBlogResponse;
import com.ckj.bloghunter.dto.response.WeChatResponse;

import lombok.extern.slf4j.Slf4j;
import me.zhyd.hunter.entity.ImageLink;
import me.zhyd.hunter.entity.VirtualArticle;
import me.zhyd.hunter.processor.BlogHunterProcessor;
import me.zhyd.hunter.processor.HunterProcessor;

/**
 * @author c.kj
 * @Description
 * @Date 2019-12-18
 * @Time 19:23
 **/
@Service
@Slf4j
public class BlogComponentServiceImpl implements BlogComponentService {

    @Autowired
    private SmallTechnologyBlogMapper smallTechnologyBlogMapper;
    @Autowired
    private RestTemplate              restTemplate;

    private String                    wxAddApi = "https://api.weixin.qq.com/tcb/databaseadd?";

    @Override
    public PreviewHunterBlogResponse previewHunterBlog(PreviewHunterBlogRequest req) {

        PreviewHunterBlogResponse previewHunterBlogResponse = new PreviewHunterBlogResponse();
        List<SmallTechnologyBlog> blogs = Lists.newArrayList();
        Optional.ofNullable(req.getUrls()).ifPresent(g -> g.parallelStream().forEach(q -> {
            boolean convertImage = true;
            HunterProcessor hunter = new BlogHunterProcessor(q.getLink(), convertImage);
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = simpleDateFormat.format(date);
            CopyOnWriteArrayList<VirtualArticle> virtualArticles = hunter.execute();
            if (virtualArticles.get(0) != null) {
                AtomicReference<String> imgUrl = new AtomicReference<>();
                Optional.ofNullable(virtualArticles.get(0).getImageLinks())
                        .ifPresent(x -> imgUrl.set(x.parallelStream().map(ImageLink::getSrcLink).findFirst().get()));
                SmallTechnologyBlog blog = SmallTechnologyBlog.builder().content(virtualArticles.get(0).getContent())
                        .id(UUID.randomUUID().toString()).title(virtualArticles.get(0).getTitle())
                        .author(virtualArticles.get(0).getAuthor())
                        .defaultImageUrl(q.getImgUrl() != null ? q.getImgUrl() : imgUrl.get())
                        .isShow(q.getIsShow() != null ? q.getIsShow().getCode() : 0).classify(0).contentType("html")
                        .createTime(q.getCreateDate() != null ? simpleDateFormat.format(q.getCreateDate()) : dateStr)
                        .totalVisits(q.getTotalVisit() != null ? q.getTotalVisit() : 1000).totalZans(200)
                        .sourceFrom(virtualArticles.get(0).getAuthor()).digest(virtualArticles.get(0).getDescription())
                        .timestamp(JSON.toJSONString(q.getCreateDate() != null ? q.getCreateDate() : date)).build();
                blog.setLabel(null);
                blog.setExtraInfo(JSON.toJSONString(blog));
                blogs.add(blog);
                if (YesEnum.YES.equals(q.getIsSave())) {
                    smallTechnologyBlogMapper.insert(blog);
                }
            }
        }));
        previewHunterBlogResponse.setBlogs(blogs);
        previewHunterBlogResponse.setSuccess(true);
        log.info("===== process success ! =====");
        return previewHunterBlogResponse;
    }

    @Override
    public WeChatResponse insertData(PreviewHunterBlogRequest req) {
        StringBuilder addApi = new StringBuilder(wxAddApi);
        String appId = BaseSystemConfig.APPID;
        String secret = BaseSystemConfig.SECRET;
        ResponseEntity<WeChatResponse> responseEntity = restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret + "", WeChatResponse.class);
        String accessToken = responseEntity.getBody().getAccess_token();
        addApi.append("access_token=").append(accessToken);
        AtomicReference<WeChatResponse> weChatResponse = new AtomicReference<>();
        req.getUrls().forEach(f -> {
            boolean convertImage = true;
            HunterProcessor hunter = new BlogHunterProcessor(f.getLink(), convertImage);
            CopyOnWriteArrayList<VirtualArticle> virtualArticles = hunter.execute();
            if (virtualArticles.get(0) != null) {
                String  content   =   StringEscapeUtils.escapeHtml4(virtualArticles.get(0).getContent()).replaceAll("\\s*", "");
                String author = virtualArticles.get(0).getAuthor();
                AtomicReference<String> imgUrl = new AtomicReference<>();
                Optional.ofNullable(virtualArticles.get(0).getImageLinks())
                        .ifPresent(x -> imgUrl.set(x.parallelStream().map(ImageLink::getSrcLink).findFirst().get()));
                String defaultImageUrl = f.getImgUrl() != null ? f.getImgUrl() : imgUrl.get();
                String title = virtualArticles.get(0).getTitle();
                Integer isShow = f.getIsShow() != null ? f.getIsShow().getCode() : 0;
                Date date = new Date();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateStr = simpleDateFormat.format(date);
                String createTime = f.getCreateDate() != null ? simpleDateFormat.format(f.getCreateDate()) : dateStr;
                Integer totalVisits = f.getTotalVisit() != null ? f.getTotalVisit() : 1000;
                Integer totalZans = 200;
                String classify = "";
                String sourceFrom=virtualArticles.get(0).getAuthor();
                String digest=virtualArticles.get(0).getDescription();
                log.info("--- start insert data ---");
                BaseInsertDTO baseInsertReqDTO = new BaseInsertDTO();
                baseInsertReqDTO.setEnv("dev-01d22a");
                String uid = UUID.randomUUID().toString();
                String label=null;
                String timestamp=JSON.toJSONString(f.getCreateDate() != null ? f.getCreateDate() : date);
                String query = "db.collection(\\\"mini_posts\\\").add({data:[{ _id:\\\"" + uid + "\\\" ,content:  \\\""
                        + content + "\\\", author:\\\"" + author + "\\\", defaultImageUrl:  \\\"" + defaultImageUrl
                        + "\\\" ,title: \\\"" + title + "\\\"  ,isShow: \\\"" + isShow
                        + "\\\" ,contentType: \\\"html\\\",createTime: \\\"" + createTime + "\\\",totalVisits: "
                        + totalVisits + ", totalZans: " + totalZans + ", sourceFrom: \\\"" + sourceFrom + "\\\", digest: \\\"" + digest + "\\\",timestamp: \\\"" + timestamp + "\\\",label: [ \\\""+ label + "\\\"],classify: \\\"" + classify + "\\\" }]})";
                baseInsertReqDTO.setQuery(query);
                weChatResponse.set(restTemplate.postForObject(addApi.toString(), baseInsertReqDTO, WeChatResponse.class));
                log.info("insert cloud data resp :{} ", JSON.toJSONString(weChatResponse));
            }
        });
        return weChatResponse.get();
    }


}
